//
//  export.cpp
//  
//
//  Created by Nikita Luzyanin on 30.11.13.
//
//

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
#include "functions.cpp"
using namespace std;

int main(int argc, char* argv[])
{
    char *pathToFS;
    
    pathToFS = argv[1];
    FILE *f;
    f = fopen(pathToFS, "rb");
    if (f == NULL) {
        cout << "Path to FS does not exist\n";
        return 1;
    }
    fclose(f);
    
    char pathToRoot[1000];
    strcpy(pathToRoot, pathToFS);
    strcat(pathToRoot, "/0");
    f = fopen(pathToRoot, "rb");
    if (f == NULL) {
        cout << "FS is not formatted\n";
        return 1;
    }
    fclose(f);
    
    char pathToFile[100];
    strcpy(pathToFile, argv[3]);
    
    char pathInFS[1000];
    strcpy(pathInFS, argv[2]);
    char metaBlock[10];
    if (findMetaBlock(pathToFS, metaBlock, pathInFS, false, false, true) != 0) {
        cout << "No File in FS\n";
        return 1;
    }
    char contentBlock[10];
    if (findContentBlock(pathToFS, metaBlock, contentBlock) != 0) {
        cout << "No Content File\n";
        return 1;
    }
    
    char pathToContentBlock[1000], pathToMetaBlock[1000], helper[20];
    char ch, nextContentBlock[10];
    strcpy(pathToContentBlock, pathToFS);
    strcat(pathToContentBlock, contentBlock);
    strcpy(pathToMetaBlock, pathToFS);
    strcat(pathToMetaBlock, metaBlock);
    
    int size;
    fstream MB;
    MB.open(pathToMetaBlock);
    MB >> helper;
    MB >> helper;
    MB >> helper;
    MB >> size;
    MB.close();
    
    fstream FSF;
    ofstream HF;
    HF.open(pathToFile);
    FSF.open(pathToContentBlock);
    
    while (size > 0) {
        FSF >> nextContentBlock;
        ch = FSF.get();
        ch = FSF.get();
        while ((!FSF.eof())&&(size > 0)) {
            HF << ch;
            size --;
            ch = FSF.get();
            
        }
        FSF.close();
        strcpy(pathToContentBlock, pathToFS);
        strcat(pathToContentBlock, nextContentBlock);
        FSF.open(pathToContentBlock);
    }
    FSF.close();
    HF.close();

    return 0;
}